import { Button, Input, Message, Radio, Tabs, Typography } from '@arco-design/web-react';
import { IconClose, IconSave } from '@arco-design/web-react/icon';
import { HasPermission } from '@src/components/ability';
import DetailCard from '@src/components/detailCard';
import DetailItem from '@src/components/detailItem';
import LoadingMask from '@src/components/loadingMask';
import { MenuTypes } from '@src/components/mainNavBar';
import { useEffect, useState } from 'react';
import { useDispatch, useSelector } from 'react-redux';
import { useNavigate, useParams } from 'react-router-dom';
import { createStoreDetailKey, detailRequest, detailUpdate } from '../../../redux/detailReducer';
import { AppStore, Record, ValidateRule } from '../../../types';
import useDict, { dictDataOptions } from '../../../utils/dict';
import { cloneDeep, validateField } from '../../../utils/utils';
import DictDataListPage from './dictDataListPage';
import { Dict } from './types';

interface Props {
  currentRouteRecord: MenuTypes;
}

const model = 'system';
const table = 'dict/type';
// 字段验证规则
const rule: ValidateRule = {};
// 字典
const SYS_NORMAL_DISABLE = 'sys_normal_disable';
export default function DictDetailPage({ currentRouteRecord }: Props) {
  // 详情id 不论代表id的字段是什么，跳转的时候都用id
  const { id } = useParams();
  // 页面标题 显示在二级菜单下面
  const pageTitle = (id === 'create' ? '新增' : '修改') + '字典';
  const dispatch = useDispatch();
  const navigate = useNavigate();
  const dictDatas = useDict(SYS_NORMAL_DISABLE);
  // 每次编辑时修改的数据
  const [detailData, setDetailData] = useState<Dict | null | undefined>({});
  // 数据验证结果
  const [errorData, setErrorData] = useState<{ [x: string]: string }>({});
  // --------------额外数据--------------------------------------

  // -----------------------------------------------------------

  // 当前详情 根据id的值区分页面模式
  const detail: Record<Dict> = useSelector(
    (state: AppStore) => state.detail?.[createStoreDetailKey({ model, table, id: id! })]
  );

  // 页面初次渲染时获取数据
  useEffect(() => {
    if (id && id !== 'create') {
      handleRefreshData();
    }
  }, []); //eslint-disable-line

  // 页面详情数据获取到后存入编辑数据
  useEffect(() => {
    if (id !== 'create' && detail?.loaded && detail?.result) {
      let result = detail?.result;
      setDetailData(result);
    }
  }, [detail]); //eslint-disable-line

  // 当前详情数据请求
  function handleRefreshData(forceRefresh?: boolean, callback?: (code?: number, msg?: string) => void) {
    if (id && id !== 'create') {
      dispatch(detailRequest({ model, table, id, forceRefresh, callback }));
    }
  }

  // 任意字段修改时存入编辑数据
  function handleChange(key: string, value: any) {
    setErrorData({});

    let data: any = cloneDeep(detailData);
    data[key] = value;
    setDetailData(data);
  }

  async function handleSave() {
    let validateRes = validateField(detailData, rule);
    setErrorData(validateRes);
    if (Object.keys(validateRes).length) return;

    LoadingMask.show('正在保存...');
    dispatch(
      detailUpdate({
        model,
        table,
        id: id!,
        detail: detailData,
        callback(code, msg, record) {
          let _msg = code === 200 ? Message.success : Message.warning;
          if (id === 'create') {
            navigate(-1);
          }
          LoadingMask.hide();
          _msg(msg ?? '');
        },
      })
    );
  }
  //----------------额外操作 / 数据-------------------

  let tabItems = [];
  if (detailData?.dictType) {
    tabItems.push({
      key: 'dictType',
      label: '值列表',
      children: <DictDataListPage type={detailData?.dictType!} />,
    });
  }
  //-------------------------------------------------

  return (
    <div className="page detail-page pb-20">
      <div className="action-bar">
        <div className="font-18 text-primary-color flex-1">{pageTitle}</div>
        <Button icon={<IconClose />} className="ml-20" type="primary" onClick={() => navigate(-1)}>
          关闭
        </Button>
        <HasPermission permission={['system:dict:edit']}>
          <Button icon={<IconSave />} className="ml-20" type="outline" onClick={handleSave}>
            保存
          </Button>
        </HasPermission>
      </div>
      <div className="detail-content">
        {/* 字段分组 每当需要分组 就加一个DetailCard 标题可隐藏 */}
        <DetailCard title="基本信息" className="mb-20">
          <DetailItem label="字典名称" error={errorData.dictName}>
            <Input value={detailData?.dictName} onChange={(v) => handleChange('dictName', v)} />
          </DetailItem>
          <DetailItem label="字典类型" error={errorData.dictType}>
            <Input value={detailData?.dictType} onChange={(v) => handleChange('dictType', v)} />
          </DetailItem>
          <DetailItem label="状态" error={errorData.status}>
            <Radio.Group
              options={dictDataOptions(dictDatas[SYS_NORMAL_DISABLE])}
              value={detailData?.status}
              onChange={(v) => handleChange('status', v)}
            />
          </DetailItem>
          <DetailItem label="备注" outlet={4} error={errorData.remark}>
            <Input.TextArea
              className="m-input-area"
              maxLength={200}
              placeholder="请输入备注"
              autoSize={{ minRows: 4 }}
              value={detailData?.remark}
              onChange={(v) => handleChange('remark', v)}
            />
          </DetailItem>
        </DetailCard>
        {tabItems.length > 0 && id !== 'create' && (
          <DetailCard className="pb-20" showTitle={false}>
            <Tabs className="bw-100">
              {tabItems.map((i) => (
                <Tabs.TabPane key={i.key} title={i.label}>
                  <Typography.Paragraph>{i.children}</Typography.Paragraph>
                </Tabs.TabPane>
              ))}
            </Tabs>
          </DetailCard>
        )}
      </div>
    </div>
  );
}
